package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品
     *
     * @param dto
     */
    @Override
    @Transactional
    public Result add(DishDTO dto) {
        //非空判断
        if (dto == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        Dish dish1 = dishMapper.getByName(dto.getName());
        if (dish1 != null) {
            return Result.error(MessageConstant.NAME_EXISTS);

        }
        //拷贝属性
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        //插入一条数据,当事物没有提交之前,我们必须返回菜品id,给新增口味获取dishId
        dishMapper.add(dish);
        //新增口味的集合,多条数据,执行批量新增,一定要拿到dishId
        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
            dishFlavorMapper.add(flavors);
        }
        return Result.success();
    }

    /**
     * 菜品分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public Result<PageResult> pageQuery(DishPageQueryDTO dto) {
        //非空判断
        if (dto.getPage() == null) {
            dto.setPage(1);
        }
        if (dto.getPageSize() == null) {
            dto.setPageSize(5);
        }
        //执行分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        //条件查询
        Page<Dish> page = dishMapper.page(dto);
        //总条数以及菜品集合
        List<Dish> dishList = page.getResult();
        //声明一个list来承载vo对象集合
        List<DishVO> dishVOList = new ArrayList<>(dishList.size());
        //为每一条数据添加菜品的分类
        dishList.forEach(dish -> {
            //声明一个vo对象
            DishVO vo = new DishVO();
            //拷贝属性
            BeanUtils.copyProperties(dish, vo);
            //获取分类名称
            Category category = categoryMapper.getById(vo.getCategoryId());
            vo.setCategoryName(category.getName());
            //写入数据到dishVOList
            dishVOList.add(vo);
        });
        //返回数据
        PageResult pageResult = new PageResult();
        pageResult.setRecords(dishList);
        pageResult.setTotal(page.getTotal());

        return Result.success(pageResult);
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Result delete(List<Long> ids) {
        //1.非空判断
        if (ids == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.查询当前菜品是否存在(根据id)
        for (Long id : ids) {
            Dish dish = dishMapper.selectById(id);
            if (dish != null) {
                //3.如果存在,判断状态,如果是起售状态,则不能删除
                if (dish.getStatus() == StatusConstant.ENABLE) {
                    return Result.error(MessageConstant.DISH_ON_SALE);
                }

            }

        }
        //4.如果存在,被套餐关联也不能删除
        List<Long> setmealIdsByDishIds = setmealMapper.getSetmealIdsByDishIds(ids);
        if (setmealIdsByDishIds!=null && setmealIdsByDishIds.size()>0){
            return Result.error(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }
        //5.如果存在,删除菜品后,口味数据也删除
        dishMapper.deleteById(ids);
        dishFlavorMapper.delectByDishId(ids);


        //6.返回
        return Result.success();
    }

    /**
     * 根据id查询菜品(数据回显)
     *
     * @param id
     * @return
     */
    @Override
    public Result getById(Long id) {
        //非空判断
        if (id==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //根据id查询当前数据
        //查询菜品
        Dish dish=  dishMapper.selectById(id);
        //查询口味
       List<DishFlavor> dishFlavors= dishFlavorMapper.selectByDishId(id);
        //口味关联到菜品中
        DishVO vo = new DishVO();
        //属性拷贝
        BeanUtils.copyProperties(dish,vo);
        vo.setFlavors(dishFlavors);
        //返回
        return Result.success(vo);
    }

    /**
     * 修改菜品
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result updateDish(DishDTO dto) {
        //非空判断
        if (dto==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        //根据id修改dish表
        Dish dish=new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.updateDishById(dish);
        //根据菜品id去删除口味表数据
        dishFlavorMapper.delectByDishId(Arrays.asList(dish.getId()));
        //插入新的口味数据到口味表中
        List<DishFlavor> flavors = dto.getFlavors();//每个DishFlavor只包含了name,并不包含dish_id
        if (flavors!=null && flavors.size()>0){
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
            dishFlavorMapper.add(flavors);
        }

        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public Result<List<Dish>> list(Long categoryId) {
        if (categoryId==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

     List<Dish> dishList= dishMapper.list(categoryId);

        return Result.success(dishList);
    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {

        List<Dish> dishList = dishMapper.list(dish.getCategoryId());

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 菜品的状态
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    public Result status(Integer status, Long id) {
        Dish dish = dishMapper.selectById(id);
        dish.setStatus(status);
        dishMapper.updateDishById(dish);
        return Result.success();
    }
}
